package servlet;

import bean.User;
import dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ServletRegisterUser extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取表单提交的用户信息
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String name = req.getParameter("name");

        // 创建 User 对象并设置属性
        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(password);
        newUser.setName(name);

        // 调用 UserDao 完成注册功能
        UserDao userDao = new UserDao();
        boolean registrationStatus = userDao.registerUser(newUser);

        if (registrationStatus) {
            // 注册成功，可以进行相应的操作，比如重定向到成功页面或者给出成功提示信息
            resp.setContentType("text/html; charset=UTF-8");
            resp.sendRedirect("index.jsp");
        } else {
            // 注册失败，可以进行相应的操作，比如重定向到失败页面或者给出失败提示信息
            resp.setContentType("text/html; charset=UTF-8");
            resp.getWriter().println("<script>alert('注册失败!'); window.location.href='register.html'</script>");
        }
    }
}
